package com.heima.behavior.advice;

import com.heima.behavior.dto.BehaviorDto;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * aop增强类
 *
 * @Author : wuqiang
 * @since : 2022-10-18
 */
@Component
@Aspect
public class BehaviorAdvice {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 行为增强
     *
     * @param pjp pjp
     * @return {@link Object}
     */
    @Around("execution(* com.heima.behavior.service.impl.*.*(..))")
    private Object behaviorAdvice(ProceedingJoinPoint pjp) {
        Object proceed = null;
        try {
            MethodSignature signature = (MethodSignature) pjp.getSignature();
            String methodName = signature.getMethod().getName();
            if (methodName.startsWith("save")) {
                //获取被增强方法的参数
                BehaviorDto arg = (BehaviorDto) pjp.getArgs()[0];
                //喜欢  保存到redis  likes:userId:artivleId
                //不喜欢  保存到redis  unlikes:userId:artivleId
                //收藏  保存到redis  collection:userId:artivleId
                //关注  保存到redis  follow:userId:artivleId
                if (arg.getOperation() == 0) {
                    redisTemplate.boundValueOps(methodName + ":" + arg.getUserId() + ":" + arg.getArticleId() + "_" + arg.getAuthorId())
                            .set("");
                } else {
                    redisTemplate.delete(methodName + ":" + arg.getUserId() + ":" + arg.getArticleId() + "_" + arg.getAuthorId());
                }
            }
            //其他不是保存行为的方法正常执行
            proceed = pjp.proceed(); //方法正常执行
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return proceed;
    }
}
